<template>
  <el-card class="form-card" shadow="hover">
    <template #header>
      <div class="card-header">
        <h3>收件人信息</h3>
        <el-button link type="primary" @click="showRecipientAddressDialog">
          从地址簿选择
        </el-button>
      </div>
    </template>
    
    <el-form-item label="收件人姓名" prop="recipientName">
      <el-input v-model="modelValue.recipientName" placeholder="请输入收件人姓名" @input="handleInput" />
    </el-form-item>
    
    <el-form-item label="收件人电话" prop="recipientPhone">
      <el-input v-model="modelValue.recipientPhone" placeholder="请输入收件人电话" @input="handleInput" />
    </el-form-item>
    
    <el-form-item label="收件省市区" prop="recipientRegion">
      <el-cascader
        v-model="modelValue.recipientRegion"
        :options="regionOptions"
        placeholder="请选择省/市/区"
        @change="handleRegionChange"
      />
    </el-form-item>
    
    <el-form-item label="详细地址" prop="recipientAddress">
      <el-input v-model="modelValue.recipientAddress" type="textarea" :rows="2" placeholder="请输入详细地址" @input="handleInput" />
    </el-form-item>
    
    <!-- 收件地址选择对话框 -->
    <el-dialog v-model="addressDialogVisible" title="选择收件地址" width="650px">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <!-- 最近地址标签页 -->
        <el-tab-pane label="最近地址" name="recent">
          <el-table 
            :data="recentAddressList" 
            style="width: 100%" 
            height="300" 
            highlight-current-row 
            @row-click="selectRecipientAddress"
            v-loading="recentLoading"
          >
            <el-table-column prop="contactName" label="联系人" min-width="80" />
            <el-table-column prop="contactPhone" label="电话" min-width="120" />
            <el-table-column prop="fullAddress" label="地址" min-width="200" show-overflow-tooltip />
            <el-table-column label="使用时间" min-width="120">
              <template #default="scope">
                <span class="recent-time">{{ formatRecentTime(scope.row.lastUsed) }}</span>
              </template>
            </el-table-column>
          </el-table>
          
          <div v-if="recentAddressList.length === 0 && !recentLoading" class="empty-state">
            <el-empty description="暂无最近使用的地址" :image-size="80" />
          </div>
        </el-tab-pane>
        
        <!-- 全部地址标签页 -->
        <el-tab-pane label="全部地址" name="all">
          <el-table 
            :data="recipientAddressList" 
            style="width: 100%" 
            height="300" 
            highlight-current-row 
            @row-click="selectRecipientAddress"
            v-loading="loading"
          >
            <el-table-column prop="contactName" label="联系人" min-width="80" />
            <el-table-column prop="contactPhone" label="电话" min-width="120" />
            <el-table-column prop="fullAddress" label="地址" min-width="200" show-overflow-tooltip />
          </el-table>
          
          <!-- 分页 -->
          <el-pagination
            v-if="total > 0"
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[5, 10, 20]"
            layout="total, sizes, prev, pager, next"
            @current-change="loadRecipientAddresses"
            @size-change="loadRecipientAddresses"
            style="margin-top: 20px; justify-content: center;"
          />
        </el-tab-pane>
      </el-tabs>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addressDialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { userApi, type Address } from '@/api/user'

// 扩展Address接口，添加最近使用时间
interface RecentAddress extends Address {
  lastUsed?: string
}

interface RecipientData {
  recipientName: string
  recipientPhone: string
  recipientRegion: string[]
  recipientAddress: string
}

const props = defineProps<{
  modelValue: RecipientData
  regionOptions: any[]
  hasAddressBook: boolean
}>()

const emit = defineEmits<{
  'update:modelValue': [value: RecipientData]
  'showAddressBook': [type: string]
  'regionChange': []
}>()

// 地址选择对话框相关
const addressDialogVisible = ref(false)
const activeTab = ref('recent') // 默认显示最近地址
const recipientAddressList = ref<Address[]>([])
const recentAddressList = ref<RecentAddress[]>([])
const loading = ref(false)
const recentLoading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(5)

const handleInput = () => {
  emit('update:modelValue', { ...props.modelValue })
}

const handleRegionChange = () => {
  emit('regionChange')
  handleInput()
}

// 显示收件地址选择对话框
const showRecipientAddressDialog = async () => {
  addressDialogVisible.value = true
  activeTab.value = 'recent' // 默认显示最近地址
  await loadRecentAddresses()
}

// 标签页切换处理
const handleTabChange = async (tabName: string) => {
  if (tabName === 'recent') {
    await loadRecentAddresses()
  } else if (tabName === 'all') {
    await loadRecipientAddresses()
  }
}

// 格式化最近使用时间
const formatRecentTime = (timestamp: string) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    return '今天'
  } else if (diffDays === 1) {
    return '昨天'
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else if (diffDays < 30) {
    const weeks = Math.floor(diffDays / 7)
    return `${weeks}周前`
  } else {
    return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })
  }
}

// 加载收件地址列表
const loadRecipientAddresses = async () => {
  try {
    loading.value = true
    const response = await userApi.queryAllReceiveAddress(currentPage.value, pageSize.value)
    
    if (response.code === 200 && response.msg) {
      recipientAddressList.value = response.msg.list || []
      total.value = response.msg.total || 0
    } else {
      ElMessage.error('获取收件地址失败')
    }
  } catch (error) {
    console.error('获取收件地址失败:', error)
    ElMessage.error('获取收件地址失败')
  } finally {
    loading.value = false
  }
}

// 加载最近使用的地址列表
const loadRecentAddresses = async () => {
  try {
    recentLoading.value = true
    
    // 获取最近使用的地址（这里模拟数据，实际应该调用专门的API）
    const response = await userApi.queryAllReceiveAddress(1, 10) // 获取前10条
    
    if (response.code === 200 && response.msg) {
      // 模拟最近使用时间数据，实际应该从API返回
      const addresses = response.msg.list || []
      recentAddressList.value = addresses.slice(0, 5).map((addr, index) => ({
        ...addr,
        lastUsed: new Date(Date.now() - index * 24 * 60 * 60 * 1000).toISOString() // 模拟使用时间
      }))
    } else {
      ElMessage.error('获取最近地址失败')
    }
  } catch (error) {
    console.error('获取最近地址失败:', error)
    ElMessage.error('获取最近地址失败')
  } finally {
    recentLoading.value = false
  }
}

// 解析完整地址，提取省市区和详细地址
const parseFullAddress = (fullAddress: string) => {
  const findMatchingRegion = (address: string, options: any[]) => {
    const result = []
    let remainingAddress = address
    
    console.log('开始解析地址:', address)
    
    // 查找省份
    for (const province of options) {
      const provinceLabel = province.label
      const provinceValue = province.value
      
      // 检查地址是否包含省份名称
      if (remainingAddress.includes(provinceLabel) || remainingAddress.includes(provinceValue)) {
        result.push(provinceValue)
        console.log('匹配到省份:', provinceValue)
        
        // 更精确的字符串替换：找到最长匹配
        let matchedProvinceName = ''
        if (remainingAddress.includes(provinceLabel)) {
          matchedProvinceName = provinceLabel
        } else if (remainingAddress.includes(provinceValue)) {
          matchedProvinceName = provinceValue
        }
        
        // 从地址开头移除省份名称
        const provinceIndex = remainingAddress.indexOf(matchedProvinceName)
        if (provinceIndex === 0) {
          remainingAddress = remainingAddress.substring(matchedProvinceName.length)
        }
        
        console.log('移除省份后的地址:', remainingAddress)
        
        // 查找城市
        if (province.children) {
          for (const city of province.children) {
            const cityLabel = city.label
            const cityValue = city.value
            
            if (remainingAddress.includes(cityLabel) || remainingAddress.includes(cityValue)) {
              result.push(cityValue)
              console.log('匹配到城市:', cityValue)
              
              // 更精确的字符串替换
              let matchedCityName = ''
              if (remainingAddress.includes(cityLabel)) {
                matchedCityName = cityLabel
              } else if (remainingAddress.includes(cityValue)) {
                matchedCityName = cityValue
              }
              
              // 从地址开头移除城市名称
              const cityIndex = remainingAddress.indexOf(matchedCityName)
              if (cityIndex === 0) {
                remainingAddress = remainingAddress.substring(matchedCityName.length)
              }
              
              console.log('移除城市后的地址:', remainingAddress)
              
              // 查找区县
              if (city.children) {
                for (const district of city.children) {
                  const districtLabel = district.label
                  const districtValue = district.value
                  
                  if (remainingAddress.includes(districtLabel) || remainingAddress.includes(districtValue)) {
                    result.push(districtValue)
                    console.log('匹配到区县:', districtValue)
                    
                    // 更精确的字符串替换
                    let matchedDistrictName = ''
                    if (remainingAddress.includes(districtLabel)) {
                      matchedDistrictName = districtLabel
                    } else if (remainingAddress.includes(districtValue)) {
                      matchedDistrictName = districtValue
                    }
                    
                    // 从地址开头移除区县名称
                    const districtIndex = remainingAddress.indexOf(matchedDistrictName)
                    if (districtIndex === 0) {
                      remainingAddress = remainingAddress.substring(matchedDistrictName.length)
                    }
                    
                    console.log('移除区县后的地址:', remainingAddress)
                    break
                  }
                }
              }
              break
            }
          }
        }
        break
      }
    }
    
    console.log('最终解析结果 - 省市区:', result, '详细地址:', remainingAddress.trim())
    
    return {
      region: result,
      detailAddress: remainingAddress.trim()
    }
  }
  
  return findMatchingRegion(fullAddress, props.regionOptions)
}

// 选择收件地址
// 选择收件地址
const selectRecipientAddress = (address: Address) => {
  console.log('选择的收件地址:', address)
  
  // 解析完整地址，提取省市区和详细地址
  const { region, detailAddress } = parseFullAddress(address.fullAddress)
  
  console.log('解析出的省市区:', region)
  console.log('解析出的详细地址:', detailAddress)
  
  // 直接修改 modelValue 的属性
  props.modelValue.recipientName = address.contactName
  props.modelValue.recipientPhone = address.contactPhone
  props.modelValue.recipientRegion = region
  props.modelValue.recipientAddress = detailAddress
  
  console.log('更新后的数据:', props.modelValue)
  
  // 发送更新事件
  emit('update:modelValue', props.modelValue)
  
  // 触发地区变更事件，用于计算距离
  emit('regionChange')
  
  addressDialogVisible.value = false
  ElMessage.success('已选择收件地址')
}
</script>

<style scoped>
.form-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.recent-time {
  color: #909399;
  font-size: 12px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

:deep(.el-tabs__content) {
  padding: 0;
}

:deep(.el-tab-pane) {
  padding: 0;
}
</style>